package com.atguigu.bigdata.chapter08;

import com.atguigu.bigdata.bean.AdsClickLog;
import com.atguigu.bigdata.util.AtguiguUtil;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ReducingState;
import org.apache.flink.api.common.state.ReducingStateDescriptor;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @Author lzc
 * @Date 2022/9/8 9:02
 */
public class Flink04_High_Project_Ads {
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        env
            .readTextFile("input/AdClickLog.csv")
            .map(new MapFunction<String, AdsClickLog>() {
                @Override
                public AdsClickLog map(String line) throws Exception {
                    String[] data = line.split(",");
                    return new AdsClickLog(
                        Long.valueOf(data[0]),
                        Long.valueOf(data[1]),
                        data[2],
                        data[3],
                        Long.parseLong(data[4]) * 1000  // 把s变成ms
                    );
                }
            })
            // 每个用户对每个广告的点击量 keyBy: 用户+广告
            .keyBy(log -> log.getUserId() + "_" + log.getAdsId())
            .process(new KeyedProcessFunction<String, AdsClickLog, String>() {
    
                private ValueState<String> yesterdayState;
                private ValueState<Boolean> isBlackListState;
                private ReducingState<Long> clickCountState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    clickCountState = getRuntimeContext().getReducingState(
                        new ReducingStateDescriptor<Long>("clickCountState", Long::sum, Long.class));
                    
                    isBlackListState = getRuntimeContext()
                        .getState(new ValueStateDescriptor<Boolean>("isBlackListState", Boolean.class));
    
    
                    yesterdayState = getRuntimeContext().getState(
                        new ValueStateDescriptor<String>("yesterdayState", String.class)
                    );
    
    
                }
                
                @Override
                public void processElement(AdsClickLog log,
                                           Context ctx,
                                           Collector<String> out) throws Exception {
                    
                    // 如果到了第二天, 点击量, 黑名单都需要重置
                    // 如何判断是否到了第二天?
                    // 定义一个状态: 存储年与日, 如果年与日发生变化, 则表示变天了(清除两个状态), 否则就是同一天
                    String yesterday = yesterdayState.value();
                    String today = AtguiguUtil.toDate(log.getTimestamp());
                    if (!today.equals(yesterday)) {
                        // 变天
                        clickCountState.clear();
                        isBlackListState.clear();
    
                        yesterdayState.update(today);
                    }
    
    
                    // 每来一条日志, 点击量 +1
                    // 如果已经加入了黑名单, 则无需聚合
                    if (isBlackListState.value() == null) {
                        clickCountState.add(1L);
                    }
                    
                    Long clickCount = clickCountState.get();
                    
                    String msg = "用户: " + log.getUserId() + " 对广告: " + log.getAdsId() + " 的点击量: " + clickCount;
                    
                    if (clickCount > 99) {
                        // 如果没有加入过黑名单, 才加, 如果已经加入, 则无需重复加入
                        if (isBlackListState.value() == null) {
                            msg += ", 达到100, 所以加入黑名单...";
                            isBlackListState.update(true);
                            out.collect(msg);
                        }
                    } else {
                        out.collect(msg);
                    }
                    
                    
                }
            })
            .print();
        
        
        env.execute();
    }
}
